import re

from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser
from users.models import User
from .models import OAuthQQUser

class OAuthQQUserSerializer(serializers.Serializer):
    """
        QQ登录创建用户序列化器
        """
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    def validate(self, attrs):
        access_token=attrs['access_token']
        password=attrs['password']
        openid=OAuthQQUser.check_save_user_token(access_token)
        if not openid:
            return serializers.ValidationError('无效的access_token')

        attrs['openid']=openid
        sms_code=attrs['sms_code']
        mobile=attrs['mobile']
        if not re.match(r'^1[34578]\d{9}$',mobile):
            return serializers.ValidationError('无效的手机号')
        redis_connect = get_redis_connection('verify_codes')
        real_sms_code=redis_connect.get('sms_code_%s' % mobile)
        real_sms_code=real_sms_code.decode()
        if sms_code.lower()!=real_sms_code.lower():
            return serializers.ValidationError('验证码错误')
        try:
            user=User.objects.get(mobile=mobile)
        except Exception as e:
            pass
        else:
            attrs['user']=user
            ret=user.check_password(password)
            if not ret:
                return serializers.ValidationError('密码错误')
        return attrs

    def create(self, validated_data):
        user=validated_data.get('user')
        if not user:
            user=User.objects.create_user(
                username=validated_data['mobile'],
                mobile=validated_data['mobile'],
                password=validated_data['password'],
            )
        # 绑定ｑｑ和用户
        OAuthQQUser.objects.create(
            openid=validated_data['openid'],
            user=user
        )
        return user